//
//  OAuthViewCtr.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/4/22.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import WebKit

class OAuthViewCtr: UIViewController {

      lazy private var webView: WKWebView = {
         self.webView = WKWebView.init(frame: self.view.bounds)
         self.webView.uiDelegate = self as WKUIDelegate
         self.webView.navigationDelegate = self as WKNavigationDelegate
         return self.webView
     }()
    
//    lazy private var webView: UIWebView = {
//        self.webView = UIWebView.init(frame: self.view.bounds)
//        self.webView.delegate = self
//        return self.webView
//    }()
    
    lazy private var progressView: UIProgressView = {
         self.progressView = UIProgressView.init(frame: CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width, height: 2))
         self.progressView.tintColor = UIColor.red
         self.progressView.trackTintColor = UIColor.white
         return self.progressView
     }()
    
    var progressObervation: NSKeyValueObservation?

    
    override func viewDidLoad() {
        super.viewDidLoad()

        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_APP_KEY)&redirect_uri=\(WB_Redirect_uri)"
        guard let url = URL(string: urlStr) else {
            return
        }
        
        view.addSubview(webView)
        view.addSubview(progressView)

        //添加属性监听
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)

//        let progress = UIView(frame: CGRect(x: 0, y: 0, width: webView.frame.width, height: 3))
//        webView.addSubview(progress)
        
//        progresslayer.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width * 0.1, height: 3)
//        progresslayer.backgroundColor = UIColor.green.cgColor
//        progress.layer.addSublayer(progresslayer)

        
        let request = URLRequest(url: url)
        webView.load(request)
//        webView.loadRequest(request)
        setNav()
        // Do any additional setup after loading the view.
    }
    
    deinit {
        webView.removeObserver(self, forKeyPath: "estimatedProgress")
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
//            progresslayer.opacity = 1
            progressView.alpha = 1.0

            let float = (change?[NSKeyValueChangeKey.newKey] as! NSNumber).floatValue
            progressView.setProgress(float, animated: true)
//            progresslayer.frame = CGRect.init(x: 0, y: 0, width: (UIScreen.main.bounds.width * CGFloat(float)) , height: 3)
            if float == 1 {
                weak var weakself = self
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: {
//                    weakself?.progresslayer.opacity = 0
                    weakself?.progressView.alpha = 0
                })
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8, execute: {
                    weakself?.progressView.setProgress(0.0, animated: false)
//                    weakself?.progresslayer.frame = CGRect.init(x: 0, y: 0, width: 0, height: 3);
                })
            }
        }else{
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
    }
    
    private func setNav(){
        let leftBtn = UIButton()
//        leftBtn.setImage(UIImage(named: "navigationbar_pop"), for: .normal)
        leftBtn.setTitle("返回", for: .normal)
        leftBtn.setTitleColor(UIColor.black, for: .normal)
        leftBtn.addTarget(self, action: #selector(leftBtnClick), for: .touchUpInside)
        leftBtn.sizeToFit()
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        
        
        let rightBtn = UIButton()
        //        leftBtn.setImage(UIImage(named: "navigationbar_pop"), for: .normal)
        rightBtn.setTitle("填充", for: .normal)
        rightBtn.setTitleColor(UIColor.black, for: .normal)
        rightBtn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        rightBtn.sizeToFit()
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
    }
    
    @objc private func leftBtnClick(){
        dismiss(animated: true, completion: nil)
    }

    @objc private func rightBtnClick(){
        let jsStr = "document.getElementById('userId').value = '13859736627';"
        webView.evaluateJavaScript(jsStr) { (result, error) in
            NSLog(message: "result = \(String(describing: result)),error = \(String(describing: error))")
        }
//        webView.stringByEvaluatingJavaScriptFromString(jsStr)
        
        let pawStr = "document.getElementById('passwd').value = 'xuejun_1992';"
        webView.evaluateJavaScript(pawStr) { (result, error) in
            NSLog(message: "result = \(String(describing: result)),error = \(String(describing: error))")
        }
    }
}

extension OAuthViewCtr: UIWebViewDelegate, WKUIDelegate, WKNavigationDelegate{

    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        
        guard let urlStr = request.url?.absoluteString else {
            return false
        }
        
        if !urlStr.hasPrefix(WB_Redirect_uri) {
            NSLog(message: "不是授权回调页面")
            return true
        }
        
        let key = "code="
        //query专门获取url中的参数，获取？后的所有内容
        guard let str = request.url!.query else { return false }
        if str.hasPrefix(key) {
            let range: Range = str.range(of: key)!
            let location: Int = str.distance(from: str.startIndex, to: range.upperBound)
            let subStrs = str.suffix(str.count - location)
            
            loadAccessToken(codeStr: String(subStrs))
        }
        
        return false
    }
    
    private func loadAccessToken(codeStr: String?){
        guard let code = codeStr else {
            return
        }
        
        let path = "oauth2/access_token"
        let parameters = ["client_id":WB_APP_KEY, "client_secret":WB_APP_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_Redirect_uri]
        
        NetWorkTools.sharInstance.post(path, parameters: parameters, success: { (objc) in
            NSLog(message: "dict =\(String(describing: objc))")
            let account = UserAcount(dict: objc as! [String: Any])
            account.loadUserInfo { (account, error) in
                if error == nil{
                    NSLog(message: "saveAccount")
                    account?.saveAccount()
                    
                    NotificationCenter.default.post(name: NSNotification.Name(ZXJSwitchRootViewController), object: false)
                    
                    // 关闭界面
                    self.leftBtnClick()
                }
            }
        }) { (error) in
            NSLog(message: "error =\(error)")
        }
        
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        guard let urlStr = navigationAction.request.url?.absoluteString else {
            decisionHandler(WKNavigationActionPolicy(rawValue: 0)!)
            return
        }
        
        if !urlStr.hasPrefix(WB_Redirect_uri) {
            NSLog(message: "不是导航授权回调页面")
            decisionHandler(WKNavigationActionPolicy(rawValue: 1)!)
            return
        }
        
        let key = "code="
        //query专门获取url中的参数，获取？后的所有内容
        guard let str = navigationAction.request.url!.query else {
            decisionHandler(WKNavigationActionPolicy(rawValue: 0)!)
            return
        }
        if str.hasPrefix(key) {
            let range: Range = str.range(of: key)!
            let location: Int = str.distance(from: str.startIndex, to: range.upperBound)
            let subStrs = str.suffix(str.count - location)
            
            loadAccessToken(codeStr: String(subStrs))
        }
        decisionHandler(WKNavigationActionPolicy(rawValue: 0)!)
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        NSLog(message: "网页由于某些原因加载失败:\(error.localizedDescription)")
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        NSLog(message: "加载失败,失败原因:\(error.localizedDescription)")
    }
}
